<template>
  <view>
    <swiper class="swapper" autoplay="true" @change="swiperChange">
      <view v-for="(item,index) in carDetail.imageUrls" :key="index" class="block">
        <swiper-item class="slide-image">
          <image :src="soonImg+item" />
        </swiper-item>
      </view>
    </swiper>
    <view class="imageCount">
      <text style="color:#E9C38C">{{current+1}}</text>
      /{{carDetail.imageUrls.length}}
    </view>
    <view class="detail-list">
      <view class="detail-item">
        <view class="p3 one-line" v-if="carDetail.description!==''">{{carDetail.description}}</view>
        <view class="detail-content">
          <view class="detail-right">
            <view class="p4" v-if="carDetail.tag!==''">
              <text v-for="(entry,ele) in carDetail.tags" :key="ele">{{entry}}</text>
            </view>
            <view class="p2">
              指导价：
              <text>{{(carDetail.lowestPrice/10000).toFixed(2)}}-{{(carDetail.highestPrice/10000).toFixed(2)}}万元</text>
            </view>
            <view
              class="detail-top"
              v-if="carDetail.specialPreference!==''&&carDetail.preferentialStrength!==''"
            >
              <text class="detail-top-p1">{{carDetail.specialPreference}}</text>
              <image :src="imgUrl+'/carSale/sd.png'" class="detail-top-img" />
              <text class="detail-top-p2">{{carDetail.preferentialStrength}}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view style="padding-bottom:68px">
    <view v-for="(item,index) in carDetail.detailImageUrls" :key="index">
      <image :src="soonImg+item" mode="widthFix" style="width:100%" />
    </view>
    </view>
    <view class="btn-box">
      <view class="btn-l" @tap="handleCar" v-if="carDetail.depositId!==''">获取底价</view>
      <view class="btn-l" @tap="handleCar" v-else style="width:690rpx">获取底价</view>
      <view class="btn-r" v-if="carDetail.depositId!==''" @tap="go">定金{{carDetail.deposit}}元</view>
    </view>
    <view v-if="!hasPhone" class="open-dialog">
      <image src="../../image/close.png" class="panel-box-close" @tap="hasPhone=true" />
      <view class="title text-center">提示</view>
      <view class="info">尚未获取手机号，无法获取想要车型</view>
      <button
        openType="getPhoneNumber"
        @GetPhoneNumber="onGetPhoneNumber"
        class="panel-box-btn"
        size="mini"
      >获取手机号</button>
    </view>
    <view class="panel-bg" v-if="!hasPhone||isAgree||isBottom"></view>
    <!--获取报价弹框-->
    <view class="bottom" v-if="isBottom" animation="animationData">
      <view class="title">获取底价</view>
      <image
        src="../../image/close.png"
        class="panel-box-close"
        @tap="isBottom=false"
        style="top:10px"
      />
      <view class="bottom-list">
        <text class="bottom-p1">您的称呼：</text>
        <input v-model="name" type="text" class="bottom-inp1" />
        <radio-group
          name="radio"
          size="mini"
          @change="handleSex"
          style="float:right;right:20px;position:absolute"
        >
          <label>
            <radio value="'先生'" checked />先生
          </label>
          <label>
            <radio value="女士" />女士
          </label>
        </radio-group>
      </view>
      <view class="bottom-list">
        <text class="bottom-p1">手机号：</text>
        <text v-if="!isClear">{{mobile|filterTel}}</text>
        <input v-model="mobile" type="number" placeholder="请输入手机号" class="bottom-inp1" v-else />
        <image :src="imgUrl+'/clone2.png'" class="bottom-img" @tap="mobile='';isClear=true" />
      </view>
      <view class="info">
        <checkbox @tap="handleAgreeChecked" :checked="agreeChecked" />
        <view @tap="isAgree=true;isBottom=false" style="display:inline-block">
          请您仔细阅读
          <text style="color:#01A0FE">《隐私协议》</text>!
        </view>
      </view>
      <view class="btn" @tap="submit">获取报价</view>
    </view>
    <!--用户协议-->
    <view v-if="isAgree" class="open-dialog agree">
      <view class="title text-center" style="padding-bottom:4px">用户协议</view>
      <agreement id="agreements" />
      <view class="btn-box">
        <view class="btn1" @tap="agreeChecked=false;isAgree=false">不同意</view>
        <view class="btn2" @tap="agreeChecked=true;isAgree=false">同意</view>
      </view>
    </view>
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import "./detail.less";
import { setGlobalData, getGlobalData } from "../../globalData.js";
import { request } from "../../util/axios.js";
import bulterApi from "@souche2014/bulter-api";
const api = bulterApi({ partner: "IOParking" });
import agreement from "./agreement.vue";
export default {
  name: "home",
  data() {
    return {
      apiBaseUrl: "https://api.cccarlife.com/api/cccl/mobile/v1", //请求头部
     //apiBaseUrl: "https://api-dev.mobile.charging.keji.io/api/cccl/mobile/v1", //请求头部（预生产）
      soonImg: "https://soonsmart.keji.io/", //接收的后台图片
      apiBaseInfo: process.env.IOParking.API_HOST, //请求头部
      imgUrl: process.env.IOParking.IMG_URL, //静态资源图片
      carDetail: {
        specialPreference: "",
        preferentialStrength: ""
      },
      isBottom: false,
      deposit:0,//定金
      depositId:null,//定金id
      posterUrl: "",
      isShow: false,
      hasPhone: true,
      mobile: "",
      sex: "先生",
      agreeChecked: true,
      isAgree: false,
      id: null,
      current: 0,
      name: "",
      isClear: false,
      shareId:null
    };
  },
  components: { agreement },
  filters: {
    //加密手机号
    filterTel(val) {
      if (val) {
        return val.substring(3, 0) + "****" + val.substring(7);
      }
    }
  },
  onShareAppMessage: function() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"]
    });
  },
  //用户点击右上角分享朋友圈
  onShareTimeline: function() {
    return {
      title: "详情页",
      query: {
        id: this.id
      }
    };
  },
  onLoad: function(options) {
    console.log(options)
    if (!getGlobalData("openId")) {
      this.wx_login();
    }
    this.id = options.id;
    this.shareId=options.shareId?options.shareId:null
    this.initData();
    api.bury("CAR_PAGE_ENTER", {carId:this.id});
  },

  methods: {
    initData() {
      var that = this;
      Taro.showLoading({
        title: "加载中"
      });
      Taro.request({
        url: this.apiBaseUrl + "/car/carinfo",
        data: {
          id: that.id
        },
        method: "GET",
        success(res) {
          console.log(res.data);
          Taro.hideLoading();
          if (res.data.isSuccess) {
            that.carDetail = res.data.data;
            that.carDetail.tags = that.carDetail.tag.split(",") || null;
            that.carDetail.detailImageUrls = that.carDetail.detailImageUrls.split(
              ","
            );
            that.carDetail.imageUrls = that.carDetail.imageUrls.split(",");
            Taro.setNavigationBarTitle({
              title: that.carDetail.name
            });
          }
        },
        fail() {
          Taro.hideLoading();
          Taro.showToast({
            title: "接口请求错误",
            icon: "none"
          });
        }
      });
    },
    go(){
      api.bury("CAR_PAGE_CLICK_FDJ");
      Taro.navigateTo({
        url: "/pages/commodityDetail/index?goodsNo="+this.carDetail.depositId //QY2109083367,QY2111043700(正式)
      });
    },
    handleCar() {
      var that = this;
      if (getGlobalData("mobile") == "" || !getGlobalData("mobile")) {
        that.hasPhone = false;
        return;
      } else {
        that.isBottom = true;
        that.mobile = getGlobalData("mobile");
        that.isClear = false;
        api.bury("CAR_PAGE_CLICK_HQDJ", {carId:this.id});
      }
    },
    currentTap(data) {
      this.posterUrl = data.posterUrl;
      this.getDetailInfo(data);
    },
    handleSex(e) {
      console.log(e);
      this.sex = e.detail.value;
    },
    submit() {
      var that = this;
      if (!that.agreeChecked) {
        Taro.showToast({
          title: "请勾选协议",
          icon: "error",
          duration: 1000,
          mask: true
        });
        return;
      }
      let pattern = /^1[3456789]\d{9}$/;
      if (!pattern.test(that.mobile)) {
        Taro.showToast({
          title: "手机号不正确",
          icon: "error",
          duration: 1000,
          mask: true
        });
        return;
      }
      let params = {
        name: that.name + that.sex,
        mobile: getGlobalData("mobile"),
        openId: getGlobalData("openId"),
        carId: that.id,
        carName: that.carDetail.name,
        housekeeperId:that.shareId
      };
      Taro.showLoading({
        title: "提交中",
        mask: true
      });
      Taro.request({
        url: this.apiBaseUrl + "/customerintention/create",
        data: params,
        method: "POST",
        success(res) {
          Taro.hideLoading();
          console.log(res.data);
          if (res.data.isSuccess) {
            api.bury("CAR_PAGE_CPA_SUCC", {carId:that.id});
            Taro.navigateTo({
              url: "../carSale/result?shareId=" + that.shareId
            });
          }
        },fail() {
          Taro.hideLoading();
          Taro.showToast({
            title: "接口请求错误",
            icon: "none"
          });
        }
      });
    },
    swiperChange: function(e) {
      var that = this;
      that.current = e.detail.current;
    },
    handleAgreeChecked() {
      this.agreeChecked = !this.agreeChecked;
    },
    wx_login() {
      var that = this;
      api
        .getUserInfo({
          scope: "all"
        })
        .then(resp => {
          if (resp.success) {
            console.log("authCode is：", resp.data);
            if (resp.data == "mock") {
              setGlobalData("openId", "oRPxj5ZrsZGRuxTa-UrzEBeLuv-s");
              setGlobalData("mobile", "17761643218");
              that.mobile = "17761643218";
              return;
            }
            that.getInfos(resp.data);
          } else {
            console.log("err is ", resp.message, "err code is ", resp.code);
          }
        });
    },
    getInfos(authCode) {
      var that = this;
      Taro.request({
        url: that.apiBaseInfo + "/weixin/souchegetuser?authCode=" + authCode,
        data: {},
        header: {
          "content-type": "application/json" // 默认值
        },
        method: "GET",
        success(res) {
          console.log("获取用户信息：", res.data);
          if (res.data.isSuccess) {
            var userOpenId = res.data.data.openId;
            setGlobalData("openId", userOpenId);
            setGlobalData("mobile", res.data.data.phoneNum);
            that.mobile = res.data.data.phoneNum;
          }
        }
      });
    },
    onGetPhoneNumber({ detail }) {
      const { encryptedData, iv } = detail;
      if (encryptedData && iv) {
        this.authPhone(encryptedData, iv);
        this.hasPhone = true;
        Taro.showLoading({
          title: "授权中，请稍后",
          mask: true
        });
      }
      api.bury("CAR_PAGE_CLICK_HQSJH", {carId:this.id});
    },
    authPhone(encryptedData, iv) {
      api
        .register({
          encryptedData: encryptedData,
          iv: iv,
          scope: "all"
        })
        .then(resp => {
          Taro.hideLoading();
          if (resp.success) {
            console.log("用户注册 ", resp.data);
            api.bury("CAR_PAGE_AGREE_EMPOWER");
            if (resp.data == "mock") {
              setGlobalData("mobile", "17761643218");
              this.mobile = getGlobalData("mobile")
                ? getGlobalData("mobile")
                : "";
              return;
            }
            this.getInfos(resp.data);
          } else {
            api.bury("CAR_PAGE_REFUSE_EMPOWER");
            console.log("err is ", resp.msg, "err code is ", resp.code);
          }
        })
        .catch(e => {
          console.log(e);
        });
    }
  }
};
</script>

